package com.tianruan.psychological.moduls.sys.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianruan.psychological.moduls.sys.user.entry.db.RoleDO;
import com.tianruan.psychological.moduls.sys.user.entry.dto.RoleDTO;
import com.tianruan.psychological.moduls.sys.user.entry.dto.RolePermissionDTO;
import com.tianruan.psychological.moduls.sys.user.mapper.RoleMapper;
import com.tianruan.psychological.moduls.sys.user.service.IRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: Dong
 * @Email: dong980514280@gmail.com
 * @Create: 2020-09-20 10:07
 * @PS
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleDO> implements IRoleService {


    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionServiceImpl rolePermissionService;

    public RolePermissionDTO getRoleById(String id){
        RoleDO roleDO = new RoleDO();
        roleDO.setId(id);
        return roleMapper.listRolePermission(roleDO).get(0);
    }

    public List<RolePermissionDTO> listRole(){
        return roleMapper.listRolePermission(new RoleDO());
    }

    @Transactional
    public RoleDTO insertRole(RoleDTO roleDTO){
        RoleDO roleDO = new RoleDO();
        BeanUtils.copyProperties(roleDTO,roleDO);
        roleMapper.insert(roleDO);
        rolePermissionService.insertRolePermission(roleDO.getId(), roleDTO.getPermissionIds());
        return roleDTO;
    }

    @Transactional
    public RoleDTO updateRole(String id, RoleDTO roleDTO){
        RoleDO roleDO = new RoleDO(roleDTO.getRole(), roleDTO.getDescription());
        roleDO.setId(id);
        roleMapper.updateById(roleDO);
        rolePermissionService.insertRolePermission(roleDO.getId(), roleDTO.getPermissionIds());
        return roleDTO;
    }
}
